import axios from 'axios'
import storage from '@/utils/storage'
import { Toast } from 'vant'

const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API
})

// 请求拦截
service.interceptors.request.use(
  (config) => {
    const token = storage.getItem('token')
    if (token) {
      config.headers.Authorization = 'Bearer ' + token
    }
    return config
  },
  (err) => {
    Promise.reject(err)
  }
)

// 响应拦截
service.interceptors.response.use(
  (response) => {
    if (response.data.code === 201) {
      Toast({
        type: 'fail',
        message: response.data.msg
      })
    } else if (response.data.code === 5001) {
      Toast({
        type: 'fail',
        message: response.data.msg
      })
    }
    return response.data
  },
  (err) => {
    console.log(err.response.status)
    // if (err.response.status === 401) {
    //   router.push('/login')
    // }
    Promise.reject(err)
  }
)

export default service
